//
//  StratrgyDetailViewController.m
//  ErWa
//
//  Created by 王阳阳 on 16/3/9.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "StratrgyDetailViewController.h"
#import "AFNetworking.h"
#import "StrategyView.h"
#import <UIImageView+WebCache.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <QuartzCore/QuartzCore.h>
#import <TencentOpenAPI/TencentOAuth.h>
@interface StratrgyDetailViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) NSMutableDictionary *dataDic;/**< 数据的字典 */
@property (nonatomic, strong) UIWebView *descriptionView;/**< 详情网页 */
@property (nonatomic, strong) UIButton *likeButton;/**< 收藏按钮 */
@property (nonatomic, strong)TencentOAuth *tencentOAuth;/**< qq */
@property (nonatomic, copy) NSString *str;//网址
@end

@implementation StratrgyDetailViewController

// 页面即将消失 将tabBar隐藏
- (void)viewWillDisappear:(BOOL)animated
{
    // tabBar隐藏
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillAppear:(BOOL)animated{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"Strategy"];
    //获取当前用户名
    NSString *nameStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    NSString *namePath = [path stringByAppendingPathComponent:nameStr];
    NSString *detailPath = [namePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@Modal.plist", @"Strategy"]];
    // 解档获取数组
    NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:detailPath];
    // 遍历数组
    for (StrategyModel *m in arr) {
        // 如果当前的题目与遍历数组中的某一个相等
        if ([m.title isEqualToString:_mainModal.title]) {
            //将喜欢按钮的状态置为红色
            _likeButton.selected = YES;
            NSLog(@"收藏过了");
        }
    }
    // tabBar显示
    self.tabBarController.tabBar.hidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;

#pragma mark - // 右上角的分享按钮
    UIBarButtonItem *shareBtton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(share:)];
    //如果当前不是轮播图点击进入的
    if (!_carouse == YES) {
        // 右上角的喜欢按钮
        self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _likeButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 7 * 6, [UIScreen mainScreen].bounds.size.height / 13, 25, 25);
        [_likeButton addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
        [_likeButton setImage:[UIImage imageNamed:@"kongaixin@2x"] forState:UIControlStateNormal];
        [_likeButton setImage:[UIImage imageNamed:@"hongaixin@2x"] forState:UIControlStateSelected];
        UIBarButtonItem *collectionButton = [[UIBarButtonItem alloc] initWithCustomView:self.likeButton];
        self.navigationItem.rightBarButtonItems = @[shareBtton, collectionButton];
    }else {
        self.navigationItem.rightBarButtonItem = shareBtton;
    }
    
    [self dataHandler];//数据处理
}
- (void)collect:(UIButton *)but{
    NSLog(@"%@", NSHomeDirectory());
    //获取攻略文件夹的路径
    NSString *StrategyPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"Strategy"];
     [[NSFileManager defaultManager] createDirectoryAtPath:StrategyPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:[StrategyPath stringByAppendingPathComponent:@"StrategyModal.plist"]];
    // 判断数组是不是存在
    if (arr) {
        NSLog(@"当前攻略数组存在");
        // 如果存在就遍历 看是不是已经收藏过
        for (StrategyModel *m in arr) {
            //判断
            if ([m.title isEqualToString:_mainModal.title]) {
                NSLog(@"已经收藏");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该攻略已经收藏过!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alert show];
                [alert dismissWithClickedButtonIndex:0 animated:YES];// 结束
                return;
            }
        }
        // 不包含就把它加到数组里面并显示已经收藏成功
        [arr addObject:_mainModal];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功啦~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        // 改变收藏按钮的背景图片
        self.likeButton.selected = YES;
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        
    } else {
        // 如果数组不存在 就创建一个新的数组 把modal加到数组里面 并显示收藏成功
        NSLog(@"创建新数组并收藏");
        // 初始化数组
        arr = [NSMutableArray array];
        [arr addObject:_mainModal];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功啦~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        // 改变收藏按钮的背景图片
        self.likeButton.selected = YES;
        
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    }
    
    // 将上一页的modal也写到本地
    [NSKeyedArchiver archiveRootObject:arr toFile:[StrategyPath stringByAppendingPathComponent:@"StrategyModal.plist"]];
    

}
#pragma mark - 分享
- (void)share:(UIButton *)sharebut{
    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:_str] title:@"dddddddd" description:nil previewImageURL:[NSURL URLWithString:_str] targetContentType:QQApiURLTargetTypeNews];
    
    
    
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
    //将内容分享到qq
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    //将内容分享到qzone
    //    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
    
    [self handleSendResult:sent];

}
/// 数据处理
- (void)dataHandler{
    self.str = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/strategy/strategy/%@", _idStr];//网址
    [AFNetworking GETWithURL:_str completion:^(id result) {
        self.dataDic = result[@"strategyModel"];
        // 下方详情的网页
        self.descriptionView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
        // 设置webview的上方距离 用来放置用户信息
        _descriptionView.scrollView.contentInset = UIEdgeInsetsMake(self.view.frame.size.height / 3, 0, 0, 0);
        //按比例适应屏幕
        //        descriptionView.scalesPageToFit = YES;
        //获取当前的html
        NSString *htmlStr = _dataDic[@"context"];
        NSString *newHtmlStr = [NSString stringWithFormat:@"<head><style>img{max-width:310px !important;}</style></head>%@", htmlStr];
        //加载webview
        [_descriptionView loadHTMLString:newHtmlStr baseURL:nil];
        // 上方的用户信息 以及 文章名称
        StrategyView *userView = [[StrategyView alloc] initWithFrame:CGRectMake(0, -self.view.frame.size.height / 3, self.view.frame.size.width, self.view.frame.size.height / 3)];
        //赋值
        NSString *photoStr = [NSString stringWithFormat:@"http://gooju.cn/simages/%@_0_9-.jpg", _dataDic[@"covorPhotoId"]];
        [userView.backImg sd_setImageWithURL:[NSURL URLWithString:photoStr]];
        [userView.userImg sd_setImageWithURL:[NSURL URLWithString:_dataDic[@"user"][@"userImageSmall"]]];
        userView.titleLabel.text = _dataDic[@"title"];
        userView.nameLabel.text = _dataDic[@"user"][@"userName"];
        // 将视图加到webview的上方
        [_descriptionView.scrollView addSubview:userView];
        //将webview加到VC上
        [self.view addSubview:_descriptionView];
      }];
}

- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            [msgbox show];
            
            
            
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        default:
        {
            break;
        }
    }
}

-(void)tencentDidLogin
{
    //    _labelTitle.text = @"登录完成";
    
    
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        //        _labelAccessToken.text = _tencentOAuth.accessToken;
        NSLog(@"%@", _tencentOAuth.accessToken);
        [_tencentOAuth accessToken];
        [_tencentOAuth openId];
        [_tencentOAuth expirationDate];
        
        [_tencentOAuth getUserInfo];
        
    }
    else
    {
        //        _labelAccessToken.text = @"登录不成功 没有获取accesstoken";
        NSLog(@"登陆不成功, 没有获取accesstoken");
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        //        _labelTitle.text = @"用户取消登录";
        NSLog(@"用户取消登陆");
    }
    else
    {
        //        _labelTitle.text = @"登录失败";
        NSLog(@"登陆失败");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
